//
//  TypeViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 2/25/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "TypeViewController.h"
#import "InventoryViewController.h"
#import "Type.h"
#import "Category.h"
#import "EditTypeViewController.h"

@interface TypeViewController () {
    
    Type *addNew;
}

@end

@implementation TypeViewController

@synthesize category;

-(void)prepareViewController {
    NSLog(@"TypeViewController: Recieved Category named: %@",[category name]);
    [self setTitle:[category name]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.allowsSelectionDuringEditing = YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    //Adding this here to allow table to automatically display changes made through local edits
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Category types count is: %i",[[category types] count]);
    return [category types].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    Type *type = category.types[indexPath.row];
    cell.textLabel.text = [type manufacturerAndName];
    
    return cell;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    if (editing) {
        //Do stuff going into the editing view
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem:)];
    } else {
        self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;

    }
}

//Function that responds to a tap on the "Add" button while in editing view
-(void)addItem:sender {
    addNew = [[Type alloc] init];
    [addNew setMyCategory:category];
    [addNew setTypeId:0];
    [self performSegueWithIdentifier:@"editType" sender:addNew];
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // make the web call to delete
        // set all params for URL
        NSString *uid = [NSString stringWithFormat:@"%d", [[category.types objectAtIndex:indexPath.row] typeId]];
        
        // generate the URL and use %20 encoding
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/type.php?secret=pass&id=%@",uid];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        //Delete locally as well
        [category.types removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    //Here you can set a specific editing style for each row, and then allow for the first empty row to have an "add" button next to it for easy insertion of a new item.
    if (indexPath.row == category.types.count) {
        return UITableViewCellEditingStyleInsert;
    }
    else {
        return UITableViewCellEditingStyleDelete;
    }
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

//Same stuff as in the Category view controller. Sets the title of the next table view to the Type that was selected.
// This both makes the interface more intuitive, and gives us an easy way to find out which Type was selected while inside InventoryViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqual: @"Segue"]) {
        InventoryViewController *nextController = segue.destinationViewController;
        nextController.type = sender;
        NSLog(@"prepareForSegue: TypeID#: %i",[sender typeId]);
    }
    if ([segue.identifier isEqual: @"editType"]) {
        EditTypeViewController *nextController = segue.destinationViewController;
        nextController.theType = sender;
        [nextController setDelegate:self];
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableView.editing == YES) {
        Type *object = category.types[indexPath.row];
        [self performSegueWithIdentifier:@"editType" sender:object];
    }
    else {
        Type *object = category.types[indexPath.row];
        NSLog(@"didSelectRowAtIndexPath ID#: %i",[object typeId]);
        //Call the segue, and pass the category that was selected along as the sender
        [self performSegueWithIdentifier:@"Segue" sender:object];
    }
}

@end
